<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ficon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/icon.png">
  <link rel="mask-icon" href="/images/icon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bqlin.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":{"gitalk":{"order":-2}},"activeClass":"gitalk"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="关键的结构体可分成以下几类： 解协议（http、rtsp、rtmp、mms）">
<meta property="og:type" content="article">
<meta property="og:title" content="FFmpeg基本API：重要结构体">
<meta property="og:url" content="https://bqlin.github.io/posts/ffmpeg_api_struct/index.html">
<meta property="og:site_name" content="權咚领域">
<meta property="og:description" content="关键的结构体可分成以下几类： 解协议（http、rtsp、rtmp、mms）">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdn.net/20130914204051125?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGVpeGlhb2h1YTEwMjA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="article:published_time" content="2021-06-28T11:27:54.000Z">
<meta property="article:modified_time" content="2021-06-28T11:27:54.000Z">
<meta property="article:author" content="權咚">
<meta property="article:tag" content="音视频">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20130914204051125?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGVpeGlhb2h1YTEwMjA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">

<link rel="canonical" href="https://bqlin.github.io/posts/ffmpeg_api_struct/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>FFmpeg基本API：重要结构体 | 權咚领域</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-105338942-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-105338942-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?98fcf61fd269408d07dcbc1e49311f9a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="權咚领域" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">權咚领域</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Making app a work of art.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bqlin.github.io/posts/ffmpeg_api_struct/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/icon.png">
      <meta itemprop="name" content="權咚">
      <meta itemprop="description" content="🤘🤯👾">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="權咚领域">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FFmpeg基本API：重要结构体
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-06-28 19:27:54" itemprop="dateCreated datePublished" datetime="2021-06-28T19:27:54+08:00">2021-06-28</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/FFmpeg/" itemprop="url" rel="index"><span itemprop="name">FFmpeg</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>11k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>10 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>关键的结构体可分成以下几类：</p>
<p><strong>解协议（http、rtsp、rtmp、mms）</strong></p>
<p><code>AVIOContext</code>、<code>URLProtocol</code>、<code>URLContext</code>主要存储音视频使用的协议类型以及状态。</p>
<p><code>URLProtocol</code>存储输入音视频使用的封装格式。每种协议都会有对应的<code>URLProtocol</code>结构体，文件也不例外。</p>
<p><strong>解封装（flv、avi、rmvb、mp4）</strong></p>
<p><code>AVFormatContext</code>主要存储音视频封装格式中的包含的信息。</p>
<p><code>AVInputFormat</code>存储输入音视频使用的封装格式，每种音视频封装格式都对应一个<code>AVInputFormat</code>结构体。</p>
<p><strong>解码（h264、mpeg2、aac、mp3）</strong></p>
<p>每个<code>AVStream</code>存储一个音频流/视频流的相关数据。</p>
<p>每个<code>AVStream</code>对应一个<code>AVCodecContext</code>，存储该流使用的解码方式的相关数据。</p>
<p>每个<code>AVCodecContext</code>对应一个<code>AVCodec</code>，包含流对应的解码器器。每种解码器对应一个<code>AVCodec</code>结构体。</p>
<p><strong>存数据</strong></p>
<p>解码前的数据结构：<code>AVPacket</code>；解码后的数据结构：<code>AVFrame</code>。每个结构体有一帧或多帧。</p>
<p>关系：</p>
<figure>
<img src="https://img-blog.csdn.net/20130914204051125?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGVpeGlhb2h1YTEwMjA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="img" /><figcaption aria-hidden="true">img</figcaption>
</figure>
<h2 id="文件操作">文件操作</h2>
<p><code>&lt;libavformat/avio.h&gt;</code></p>
<h3 id="aviodircontext">AVIODirContext</h3>
<p>操作目录上下文，承载目录信息。</p>
<h3 id="aviodirentry">AVIODirEntry</h3>
<p>目录内容项，承载文件/目录详细信息。用于存放文件名、文件大小等信息。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;libavformat/avio.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 删除文件</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avpriv_io_delete</span><span class="params">(<span class="type">const</span> <span class="type">char</span>* url)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 移动或重命名</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avpriv_io_move</span><span class="params">(<span class="type">const</span> <span class="type">char</span>* url_src, <span class="type">const</span> <span class="type">char</span>* url_dst)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 打开目录，会分配AVIODirContext</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avio_open_dir</span><span class="params">(AVIODirContext** s, <span class="type">const</span> <span class="type">char</span>* url, AVDictionary** options)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 读取目录，结果输出到AVIODirEntry</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avio_read_dir</span><span class="params">(AVIODirContext* s, AVIODirEntry** next)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 关闭目录（释放资源）</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avio_close_dir</span><span class="params">(AVIODirContext** s)</span>;</span><br></pre></td></tr></table></figure>
<h2 id="数据包操作">数据包操作</h2>
<p><code>&lt;libavformat/avformat.h&gt;</code></p>
<h3 id="avformatcontext">AVFormatContext</h3>
<p>统领全局的基本结构体。主要用于处理封装格式。</p>
<ul>
<li><code>struct AVInputFormat *iformat</code>：输入数据的封装格式，由<code>avformat_open_input</code>设置，仅仅在解封装时使用。</li>
<li><code>struct AVOutputFormat *oformat</code>：输出数据的封装格式，必须由使用者在<code>avformat_write_header</code>前设置，由封装时使用。</li>
<li><code>priv_data</code>：格式私有数据。在封装中，由<code>avformat_write_header</code>设置；在解封装中，由<code>avformat_open_input</code>设置。</li>
<li><code>AVIOContext *pb</code>：输入输出上下文。如果<code>iformat/oformat.flags</code>设置为<code>AVFMT_NOFILE</code>的话，该字段不需要设置。对于解封装，需要在<code>avformat_open_input</code>前设置，或由<code>avformat_open_input</code>设置；对于封装，在<code>avformat_write_header</code>前设置。</li>
<li><code>ctx_flags</code>：码流的信息，表明码流属性的的信号。由<code>libavformat</code>设置，例如<code>AVFMTCTX_NOHEADER</code>。</li>
<li><code>nb_streams</code>：指<code>AVFormatContext.streams</code>的数量，必须由<code>avformat_new_stream</code>设置，不能由其他代码改动。</li>
<li><code>AVStream **streams</code>：文件中所有码流的列表，新的码流创建使用<code>avformat_new_stream</code>函数。解封装中，码流由<code>avformat_open_input</code>创建。 如果<code>AVFMTCTX_NOHEADER</code>被设置，新的码流可以出现在<code>av_read_frame</code>中。封装中，码流在<code>avformat_write_header</code>之前由用户创建。它的释放是由<code>avformat_free_context</code>完成的。</li>
<li><code>filename</code>：输入或输出的文件名，解封装中由<code>avformat_open_input</code>设置，封装中在使用<code>avformat_write_header</code>前由调用者设置。</li>
<li><code>int64_t duration</code>：码流的时长。</li>
<li><code>bit_rate</code>：比特率。</li>
<li><code>enum AVCodecID video_codec_id</code></li>
<li><code>AVDictionary *metadata</code>：元数据，适用于整个文件。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建与销毁</span></span><br><span class="line">AVFormatContext* <span class="title function_">avformat_alloc_context</span><span class="params">()</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">avformat_free_context</span><span class="params">(AVFormatContext* s)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/// 其他创建方式</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 打开现有的媒体文件</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avformat_open_input</span><span class="params">(AVFormatContext **ps, <span class="type">const</span> <span class="type">char</span> *url, AVInputFormat *fmt, AVDictionary **options)</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">avformat_close_input</span><span class="params">(AVFormatContext* s)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 根据路径猜测并创建。其内部为avformat_alloc_context+av_guess_format+赋值</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">avformat_alloc_output_context2</span><span class="params">(AVFormatContext **ctx, AVOutputFormat *oformat, <span class="type">const</span> <span class="type">char</span> *format_name, <span class="type">const</span> <span class="type">char</span> *filename)</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">avformat_free_context</span><span class="params">(AVFormatContext *s)</span>；</span><br></pre></td></tr></table></figure>
<h3 id="avstream">AVStream</h3>
<p>流/轨信息（不包含数据）。</p>
<ul>
<li><code>index</code>：在AVFormatContext的流索引。</li>
<li><del><code>AVCodecContext *codec</code></del>：已被弃用，改成<code>AVCodecParameters *codecpar</code>：编解码信息。</li>
<li><code>AVRational time_base</code>：时间单位。</li>
<li><code>duration</code>：流长度。</li>
<li><code>AVDictionary *metadata</code>：元数据信息。</li>
<li><code>AVRational avg_frame_rate</code>：平均帧率。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建与销毁</span></span><br><span class="line">AVStream* <span class="title function_">avformat_new_stream</span><span class="params">(AVFormatContext* s, <span class="type">const</span> AVCodec* c)</span>;</span><br><span class="line"><span class="comment">// 随avformat_free_context一起销毁</span></span><br></pre></td></tr></table></figure>
<h3 id="aviocontext">AVIOContext</h3>
<p>输入输出对应的结构体。</p>
<ul>
<li><code>unsigned char *buffer</code>：缓存开始位置。</li>
<li><code>buffer_size</code>：缓存大小。</li>
<li><code>unsigned char *buf_ptr</code>：当前指针读取到的位置。</li>
<li><code>unsigned char *buf_end</code>：缓存结束的位置。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建与销毁</span></span><br><span class="line">AVIOContext* <span class="title function_">avio_alloc_context</span><span class="params">(</span></span><br><span class="line"><span class="params">    <span class="type">unsigned</span> <span class="type">char</span>* buffer, <span class="type">int</span> buffer_size,</span></span><br><span class="line"><span class="params">    <span class="type">int</span> write_flag, <span class="type">void</span>* opaque,</span></span><br><span class="line"><span class="params">    <span class="type">int</span>(*)(<span class="type">void</span> *opaque, <span class="type">uint8_t</span> *buf, <span class="type">int</span> buf_size) read_packet,</span></span><br><span class="line"><span class="params">    <span class="type">int</span>(*)(<span class="type">void</span> *opaque, <span class="type">uint8_t</span> *buf, <span class="type">int</span> buf_size) write_packet,</span></span><br><span class="line"><span class="params">    <span class="type">int64_t</span>(*)(<span class="type">void</span> *opaque, <span class="type">int64_t</span> offset, <span class="type">int</span> whence) seek</span></span><br><span class="line"><span class="params">)</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">avio_context_free</span><span class="params">(AVIOContext** s)</span>;</span><br></pre></td></tr></table></figure>
<h3 id="avpacket">AVPacket</h3>
<p>压缩数据包，压缩域结构体，一个或多个压缩数据帧。这是流操作中的核心数据。</p>
<p>对于视频数据，只包含一帧压缩数据；对于音频数据，可能包含多帧压缩数据。</p>
<p>定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">AVPacket</span>&#123;</span></span><br><span class="line">	AVBufferRef *buf;</span><br><span class="line">	<span class="type">int64_t</span>      pts;</span><br><span class="line">	<span class="type">int64_t</span>      dts;</span><br><span class="line">	<span class="type">uint8_t</span>    *data;</span><br><span class="line">	<span class="type">int</span>         size;</span><br><span class="line">	<span class="type">int</span> stream_index;</span><br><span class="line">	<span class="type">int</span>        flags;</span><br><span class="line">	AVPacketSideData *side_data;</span><br><span class="line">	<span class="type">int</span> side_data_elems;</span><br><span class="line">	<span class="type">int</span>   duration;</span><br><span class="line">	<span class="type">int64_t</span> pos;</span><br><span class="line">	<span class="type">int64_t</span> convergence_duration;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>pts</code>：显示时间戳，它的单位是 <code>AVStream-&gt;time_base</code>；如果在文件中没有保存这个值，它被设置为 <code>AV_NOPTS_VALUE</code>。由于图像显示不可能早于图像解压，因此 PTS 必须比 DTS（解码时间戳）大或者相等。某些文件格式中可能会使用 PTS/DTS 表示其他含义，此时时间戳必须转为真正的时间戳才能保存到 AVPacket 结构中。</li>
<li><code>dts</code>：解码时间戳，它的单位是 <code>AVStream-&gt;time_base</code>，表示压缩视频解码的时间，如果文件中没有保存该值，它被设置为 <code>AV_NOPTS_VALUE</code>。</li>
<li><code>data</code>：指向真正的压缩编码的数据。</li>
<li><code>size</code>：表示该 AVPacket 结构中 data 字段所指向的压缩数据的大小。</li>
<li><code>stream_index</code>：标识该 AVPacket 结构所属的视频流或音频流。</li>
<li><code>duration</code>：该 AVPacket 包以 <code>AVStream-&gt;time_base</code> 为单位，所持续的时间，0 表示未知，或者为显示时间戳的差值(next_pts - this pts)。</li>
<li><code>pos</code>：表示该 AVPacket 数据在媒体中的位置，即字节偏移量。</li>
</ul>
<p>直接创建：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 可在栈或堆中创建</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 类似的，如果AVPacket是在堆创建的，则要配合使用这两个API</span></span><br><span class="line">AVPacket *<span class="title function_">av_packet_alloc</span><span class="params">()</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">av_packet_free</span><span class="params">(AVPacket** pkt)</span>;</span><br></pre></td></tr></table></figure>
<h4 id="填充方式一av_read_frame">填充方式一：av_read_frame</h4>
<p>通过AVFormatContext可读取一般的媒体容器文件。</p>
<p>这里的读取数据包的方法命名为<code>av_read_frame</code>只是历史遗留问题，以前的数据包也是用frame命名的，后面才改了过来。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 每次读取帧后，要对应减引用计数。</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">av_read_frame</span><span class="params">(AVFormatContext* s, AVPacket *pkt)</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">av_packet_unref</span><span class="params">(AVPacket* pkt)</span>;</span><br></pre></td></tr></table></figure>
<h4 id="填充方式二av_parser_parse2">填充方式二：av_parser_parse2</h4>
<p>通过AVCodecParserContext、AVCodecContext解析buffer，得出数据包的主要信息。只能针对音视频裸流进行解析。该方法只是解析，即还要借助其他API读取获得buffer。</p>
<p>AVCodecParser用于解析输入的数据流并把它们分成一帧一帧的压缩编码数据。比较形象的说法就是把长长的一段连续的数据“切割”成一段段的数据。 <code>av_parser_parse2()</code>：解析数据获得一个Packet， 从输入的数据流中分离出一帧一帧的压缩编码数据。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">av_parser_parse2</span><span class="params">(AVCodecParserContext *s, AVCodecContext *avctx, <span class="type">uint8_t</span> **poutbuf, <span class="type">int</span> *poutbuf_size, <span class="type">const</span> <span class="type">uint8_t</span> *buf, <span class="type">int</span> buf_size, <span class="type">int64_t</span> pts, <span class="type">int64_t</span> dts, <span class="type">int64_t</span> pos)</span></span><br></pre></td></tr></table></figure>
<p>由于传入的buffer可以有多个数据包，所以需要循环读取：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (data_size &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="comment">// 返回以解析的大小，若小于buffer的大小，则会再次进行循环解析</span></span><br><span class="line">    ret = av_parser_parse2(parser, c, &amp;pkt-&gt;data, &amp;pkt-&gt;size,</span><br><span class="line">                           data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (ret &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;Error while parsing\n&quot;</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    data      += ret;</span><br><span class="line">    data_size -= ret;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pkt-&gt;size) &#123;</span><br><span class="line">        <span class="comment">// 这时获得一个合法的数据包</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="编解码">编解码</h2>
<p><code>&lt;libavcodec/avcodec.h&gt;</code></p>
<h3 id="avcodec">AVCodec</h3>
<p>编码器结构体，通过它转换AVFrame/AVPacket。</p>
<p>定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">AVCodec</span>&#123;</span></span><br><span class="line">	<span class="type">const</span> <span class="type">char</span> *name;</span><br><span class="line">    <span class="type">const</span> <span class="type">char</span> *long_name;</span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVMediaType</span> <span class="title">type</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVCodecID</span> <span class="title">id</span>;</span></span><br><span class="line">    <span class="type">int</span> capabilities;</span><br><span class="line">    <span class="type">const</span> AVRational *supported_framerates; <span class="comment">///&lt; array of supported framerates, or NULL if any, array is terminated by &#123;0,0&#125;</span></span><br><span class="line">    <span class="type">const</span> <span class="class"><span class="keyword">enum</span> <span class="title">AVPixelFormat</span> *<span class="title">pix_fmts</span>;</span>     <span class="comment">///&lt; array of supported pixel formats, or NULL if unknown, array is terminated by -1</span></span><br><span class="line">    <span class="type">const</span> <span class="type">int</span> *supported_samplerates;       <span class="comment">///&lt; array of supported audio samplerates, or NULL if unknown, array is terminated by 0</span></span><br><span class="line">    <span class="type">const</span> <span class="class"><span class="keyword">enum</span> <span class="title">AVSampleFormat</span> *<span class="title">sample_fmts</span>;</span> <span class="comment">///&lt; array of supported sample formats, or NULL if unknown, array is terminated by -1</span></span><br><span class="line">    <span class="type">const</span> <span class="type">uint64_t</span> *channel_layouts;         <span class="comment">///&lt; array of support channel layouts, or NULL if unknown. array is terminated by 0</span></span><br><span class="line">    <span class="type">uint8_t</span> max_lowres;                     <span class="comment">///&lt; maximum value for lowres supported by the decoder, no direct access, use av_codec_get_max_lowres()</span></span><br><span class="line">    <span class="type">const</span> AVClass *priv_class;              <span class="comment">///&lt; AVClass for the private context</span></span><br><span class="line">    <span class="type">const</span> AVProfile *profiles;              <span class="comment">///&lt; array of recognized profiles, or NULL if unknown, array is terminated by &#123;FF_PROFILE_UNKNOWN&#125;</span></span><br><span class="line">    <span class="type">int</span> priv_data_size;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">AVCodec</span> *<span class="title">next</span>;</span></span><br><span class="line">    <span class="type">int</span> (*init_thread_copy)(AVCodecContext *);</span><br><span class="line">    <span class="type">int</span> (*update_thread_context)(AVCodecContext *dst, <span class="type">const</span> AVCodecContext *src);</span><br><span class="line">    <span class="type">const</span> AVCodecDefault *defaults;</span><br><span class="line">    <span class="type">void</span> (*init_static_data)(<span class="keyword">struct</span> AVCodec *codec);</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> (*init)(AVCodecContext *);</span><br><span class="line">    <span class="type">int</span> (*encode_sub)(AVCodecContext *, <span class="type">uint8_t</span> *buf, <span class="type">int</span> buf_size,</span><br><span class="line">    <span class="type">int</span> (*encode2)(AVCodecContext *avctx, AVPacket *avpkt, <span class="type">const</span> AVFrame *frame,</span><br><span class="line">                   <span class="type">int</span> *got_packet_ptr);</span><br><span class="line">    <span class="type">int</span> (*decode)(AVCodecContext *, <span class="type">void</span> *outdata, <span class="type">int</span> *outdata_size, AVPacket *avpkt);</span><br><span class="line">    <span class="type">int</span> (*close)(AVCodecContext *);</span><br><span class="line">    <span class="type">void</span> (*flush)(AVCodecContext *);</span><br><span class="line">    <span class="type">int</span> caps_internal;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>name</code>：具体的 CODEC 的名称的简短描述，比如“HEVC”、“H264”等。</li>
<li><code>long_name：CODEC</code> 名称的详细描述，比如“HEVC (High Efficiency Video Coding)”。</li>
<li><code>id</code>：唯一标识的 CODEC 类型，比如 AV_CODEC_ID_HEVC。</li>
<li><code>type</code>：媒体类型的字段，它是 enum 型的，表示视频、音频、字幕等，比如<code>AVMEDIA_TYPE_VIDEO</code>、<code>AVMEIDA_TYPE_AUDIO</code>。</li>
<li><code>supported_framerates</code>：支持的视频帧率的数组，以{0，0}作为结束。</li>
<li><code>pix_fmts</code>：编解码器支持的图像格式的数组，以 -1 作为结束。</li>
<li><code>profiles</code>：编解码器支持的 Profile，以 HEVC 为例，包含“Main”、“Main10”、“Main Still Picture”。</li>
</ul>
<p>每一个编解码器对应一个 AVCodec 结构体，对应一种编解码方式，比如 HEVC、AVC、MPEG2、MPEG4、VP6、VP8、VP9等。以 HEVC 为例，FFMpeg中关于 AVCodec 的定义如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">AVCodec ff_hevc_decoder = &#123;</span><br><span class="line">    .name                  = <span class="string">&quot;hevc&quot;</span>,</span><br><span class="line">    .long_name             = NULL_IF_CONFIG_SMALL(<span class="string">&quot;HEVC (High Efficiency Video Coding)&quot;</span>),</span><br><span class="line">    .type                  = AVMEDIA_TYPE_VIDEO,</span><br><span class="line">    .id                    = AV_CODEC_ID_HEVC,</span><br><span class="line">    .priv_data_size        = <span class="keyword">sizeof</span>(HEVCContext),</span><br><span class="line">    .priv_class            = &amp;hevc_decoder_class,</span><br><span class="line">    .init                  = hevc_decode_init,</span><br><span class="line">    .close                 = hevc_decode_free,</span><br><span class="line">    .decode                = hevc_decode_frame,</span><br><span class="line">    .flush                 = hevc_decode_flush,</span><br><span class="line">    .update_thread_context = hevc_update_thread_context,</span><br><span class="line">    .init_thread_copy      = hevc_init_thread_copy,</span><br><span class="line">    .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |</span><br><span class="line">                             AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_FRAME_THREADS,</span><br><span class="line">    .profiles              = NULL_IF_CONFIG_SMALL(profiles),</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>AVCodec通常用法：</p>
<ol type="1">
<li>根据特定ID找到特定的编解码器；</li>
<li>根据特定编解码器分配出特定的描述编解码上下文的 AVCodecContext 结构体；</li>
<li>打开编解码器；</li>
<li>调用编解码器进行编解码。</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">AVCodec *codec = <span class="literal">NULL</span>;</span><br><span class="line">AVCodecContext *ctx = <span class="literal">NULL</span>;</span><br><span class="line"></span><br><span class="line">codec = avcodec_find_decoder(origin_ctx-&gt;codec_id);</span><br><span class="line">ctx = avcodec_alloc_context3(codec);</span><br><span class="line">avcodec_open2(ctx, codec, <span class="literal">NULL</span>);</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<h3 id="avcodeccontext">AVCodecContext</h3>
<p>编解码上下文。连接编解码各个过程。最复杂的结构体，里面定义的变量有些是编码时候用到，有些是解码时候用到。</p>
<ul>
<li><code>codec_type</code>：编解码器的类型，如音频、视频、字幕。</li>
<li><code>AVCdec *codec</code>：编解码器对象。</li>
<li><code>bit_rate</code>：平均比特率。</li>
<li><code>width</code>、<code>height</code>：视频的宽高。</li>
<li><code>refs</code>：运动估计参考帧的个数。</li>
<li><code>sample_rate</code>：采样率。</li>
<li><code>channels</code>：声道数。</li>
</ul>
<p>AVCodecContext 使用 <code>avcodec_alloc_context3</code> 分配，该函数除了分配 AVCodecContext 外，还会初始化默认的字段。分配的内存必须通过 <code>avcodec_free_context</code> 释放。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建与销毁</span></span><br><span class="line">AVCodecContext** <span class="title function_">avcodec_alloc_context3</span><span class="params">(<span class="type">const</span> AVCodec* codec)</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">avcodec_free_context</span><span class="params">(AVCodecContext** avctx)</span>;</span><br></pre></td></tr></table></figure>
<h3 id="avframe">AVFrame</h3>
<p>未压缩数据帧，像素域结构体，（视频对应RGB/YUV像素数据，音频对应PCM采样数据）。</p>
<p>定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">AVFrame</span>&#123;</span></span><br><span class="line">	<span class="type">uint8_t</span> *data[AV_NUM_DATA_POINTERS];</span><br><span class="line">	<span class="type">int</span> linesize[AV_NUM_DATA_POINTERS];</span><br><span class="line">	<span class="type">uint8_t</span> **extended_data;</span><br><span class="line">	<span class="type">int</span> width, height;</span><br><span class="line">	<span class="type">int</span> nb_samples; <span class="comment">/* number of audio samples(per channel) described by this frame */</span></span><br><span class="line">	<span class="type">int</span> format;</span><br><span class="line">	<span class="type">int</span> key_frame; <span class="comment">/* 1-&gt;keyframe, 0-&gt;not*/</span></span><br><span class="line">	<span class="class"><span class="keyword">enum</span> <span class="title">AVPictureType</span> <span class="title">pict_type</span>;</span></span><br><span class="line">	AVRational sample_aspect_ratio;</span><br><span class="line">	<span class="type">int64_t</span> pts;</span><br><span class="line">	<span class="type">int64_t</span> pkt_pts;</span><br><span class="line">	<span class="type">int64_t</span> pkt_dts;</span><br><span class="line">	<span class="type">int</span> coded_picture_number;</span><br><span class="line">	<span class="type">int</span> display_picture_number;</span><br><span class="line">	<span class="type">int</span> quality;</span><br><span class="line">	<span class="type">void</span> *opaque; <span class="comment">/* for some private data of the user */</span></span><br><span class="line">	<span class="type">uint64_t</span> error[AV_NUM_DATA_POINTERS];</span><br><span class="line">	<span class="type">int</span> repeat_pict;</span><br><span class="line">	<span class="type">int</span> interlaced_frame;</span><br><span class="line">	<span class="type">int</span> top_field_first;	<span class="comment">/* If the content is interlaced, is top field displayed first */</span></span><br><span class="line">	<span class="type">int</span> palette_has_changed;</span><br><span class="line">    <span class="type">int64_t</span> reordered_opaque;</span><br><span class="line">    <span class="type">int</span> sample_rate;    <span class="comment">/*Sample rate of the audio data*/</span></span><br><span class="line">    <span class="type">uint64_t</span> channel_layout; <span class="comment">/*channel layout of the audio data*/</span></span><br><span class="line">    AVBufferRef *buf[AV_NUM_DATA_POINTERS];</span><br><span class="line">    AVBufferRef **extended_buf;</span><br><span class="line">    <span class="type">int</span> nb_exteneded_buf;</span><br><span class="line">    AVFrameSideData **side_data;</span><br><span class="line">    <span class="type">int</span> nb_side_data;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> flags;</span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVColorRange</span> <span class="title">color_range</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVColorPrimaries</span> <span class="title">color_primaries</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVColorTransferCharacteristic</span> <span class="title">color_trc</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVColorSpace</span> <span class="title">colorspace</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">enum</span> <span class="title">AVChromaLocation</span> <span class="title">chroma_location</span>;</span></span><br><span class="line"></span><br><span class="line">    <span class="type">int64_t</span> best_effort_timestamp;</span><br><span class="line">    <span class="type">int64_t</span> pkt_pos;</span><br><span class="line">    <span class="type">int64_t</span> pkt_duration;</span><br><span class="line">    AVDictionary *metadata;</span><br><span class="line">    <span class="type">int</span> decode _error_flags;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> channels;</span><br><span class="line">    <span class="type">int</span> pkt_size;</span><br><span class="line">    AVBufferRef *qp_table_buf;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>data</code>：指向图片或信道的指针，与初始化时分配的大小可能不同，一些解码器取数据范围超出(0,0)-(width, height)，具体请查看<code>avcodec_align_dimensions2()</code>方法。一些过滤器或扫描器读数据时可能会超过 16 字节，所以当它们使用时，必须额外分配 16 字节。对于 packed 格式的数据(例如 RGB24)，会存放到 data[0] 里面；对于 planar 格式的数据(例如 YUV420P)，则会分开 data[0]/data[1]/data[2]（YUV420P 中 data[0] 存放 Y，data[1] 存放 U，data[2] 存放 V）。</li>
<li><code>linesize</code>：对于视频数据，表示每个图像行的字节大小；对于音频数据，表示每个 Plane 的字节大小，只有linesize[0]可以设置，对于plane 音频，每个信道 channel 必须是相同的。对于视频的 linesize 应为 CPU 的对准要求的倍数，一般为 32 的倍数。注意 linesize 可大于可用的数据的尺寸，有可能存在由于性能原因额外填充。</li>
<li><code>width</code>/<code>height</code>：视频的宽高。</li>
<li><code>format</code>：帧格式，-1表示未设置的帧格式。对于视频帧，该值为 enum 类型的 AVPixelFormat，例如 <code>AV_PIX_FMT_YUV420P</code>；对于音频帧，该值为 enum 型的 AVSampleFormat，例如 <code>AV_SAMPLE_FMT_S16</code>。</li>
<li><code>key_frame</code>：关键帧，1 表示关键帧，0 表示非关键帧。</li>
<li><code>pict_type</code>：帧图片类型，例如 I/P/B。</li>
<li><code>sample_aspect_ration</code>：帧像素的宽高比，使用 AVRational 表示。</li>
<li><code>pts</code>：显示时间戳，单位为 <code>time_base</code>。</li>
<li><code>pkt_pts</code>：该 PTS 是从 AVPacket 结构中拷贝过来的；与之对应的是<code>pkt_dts</code>。</li>
<li><code>coded_picture_number</code>/<code>display_picture_number</code>：解码序列号和显示序列号（Display Order/Decoded Order）。</li>
<li><code>interlaced_frame</code>：表示该帧为隔行（interlace）码流或者为逐行（progressive）码流。</li>
<li><code>top_field_first</code>：对于隔行码流，表示该它是 top first or bottom first。</li>
</ul>
<p>AVFrame 结构体通常只需分配一次，之后即可通过保存不同的数据来重复多次使用，比如一个 AVFrame 结构可以保存从解码器中解码出的多帧数据。此时，就可以使用<code>av_frame_unref()</code>释放任何由 Frame 保存的参考帧并还原回最原始的状态。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建与销毁</span></span><br><span class="line">AVFrame* <span class="title function_">av_frame_alloc</span><span class="params">()</span>;</span><br><span class="line"><span class="type">void</span> <span class="title function_">av_frame_free</span><span class="params">(AVFrame** frame)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 填充空间</span></span><br><span class="line">av_image_fill_arrays(</span><br><span class="line">    <span class="type">uint8_t</span>* dst_data[<span class="number">4</span>], <span class="type">int</span> dst_linesize[<span class="number">4</span>], <span class="type">const</span> <span class="type">uint8_t</span>* src,</span><br><span class="line">    <span class="keyword">enum</span> AVPixelFormat pix_fmt, <span class="type">int</span> width, <span class="type">int</span> height, <span class="type">int</span> align</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E9%9F%B3%E8%A7%86%E9%A2%91/" rel="tag"># 音视频</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/ffmpeg_command/" rel="prev" title="FFmpeg常用命令">
      <i class="fa fa-chevron-left"></i> FFmpeg常用命令
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/ffmpeg_api_new_deprecated/" rel="next" title="FFmpeg新老API">
      FFmpeg新老API <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C"><span class="nav-text">文件操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#aviodircontext"><span class="nav-text">AVIODirContext</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#aviodirentry"><span class="nav-text">AVIODirEntry</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E5%8C%85%E6%93%8D%E4%BD%9C"><span class="nav-text">数据包操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#avformatcontext"><span class="nav-text">AVFormatContext</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avstream"><span class="nav-text">AVStream</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#aviocontext"><span class="nav-text">AVIOContext</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avpacket"><span class="nav-text">AVPacket</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A1%AB%E5%85%85%E6%96%B9%E5%BC%8F%E4%B8%80av_read_frame"><span class="nav-text">填充方式一：av_read_frame</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A1%AB%E5%85%85%E6%96%B9%E5%BC%8F%E4%BA%8Cav_parser_parse2"><span class="nav-text">填充方式二：av_parser_parse2</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BC%96%E8%A7%A3%E7%A0%81"><span class="nav-text">编解码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#avcodec"><span class="nav-text">AVCodec</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avcodeccontext"><span class="nav-text">AVCodecContext</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#avframe"><span class="nav-text">AVFrame</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="權咚"
      src="/images/icon.png">
  <p class="site-author-name" itemprop="name">權咚</p>
  <div class="site-description" itemprop="description">🤘🤯👾</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">84</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/bqlin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;bqlin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/hearingdog" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;hearingdog" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/metal-reference-translation" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;metal-reference-translation" rel="noopener" target="_blank">Metal内参</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/wwdc21" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;wwdc21" rel="noopener" target="_blank">WWDC21 内参</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">權咚</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">279k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '7ed324dbfd2741c35c0e',
      clientSecret: '75a59e1f6a55202c4a1b0ec3570ad5b5dccbc390',
      repo        : 'bqlin.github.io',
      owner       : 'bqlin',
      admin       : ['bqlin'],
      id          : 'a89256edb99ac7330228647ba41d6d6c',
        language: 'zh-CN',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","vOffset":-100},"mobile":{"show":false,"scale":0.5},"log":false});</script></body>
</html>
